<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico">
  <link rel="mask-icon" href="/images/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wwwttttj.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="spring 效验架构整理1.spring @Validated1 @Validated 和@Valid 区别Validated带分组功能 而Valid没有实现(@Validated supporting the specification of validation groups) Variant of JSR-303 拥有以下注解 12345AssertFalse  AssertTrue  D">
<meta property="og:type" content="article">
<meta property="og:title" content="spring-校验框架整理">
<meta property="og:url" content="https://wwwttttj.gitee.io/2020/09/24/spring-%E6%A0%A1%E9%AA%8C%E6%A1%86%E6%9E%B6%E6%95%B4%E7%90%86/index.html">
<meta property="og:site_name" content="wwwblog">
<meta property="og:description" content="spring 效验架构整理1.spring @Validated1 @Validated 和@Valid 区别Validated带分组功能 而Valid没有实现(@Validated supporting the specification of validation groups) Variant of JSR-303 拥有以下注解 12345AssertFalse  AssertTrue  D">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-09-24T01:18:37.000Z">
<meta property="article:modified_time" content="2020-09-24T01:20:47.321Z">
<meta property="article:author" content="wwwttttj">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://wwwttttj.gitee.io/2020/09/24/spring-%E6%A0%A1%E9%AA%8C%E6%A1%86%E6%9E%B6%E6%95%B4%E7%90%86/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>spring-校验框架整理 | wwwblog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="wwwblog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">wwwblog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wwwttttj.gitee.io/2020/09/24/spring-%E6%A0%A1%E9%AA%8C%E6%A1%86%E6%9E%B6%E6%95%B4%E7%90%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="wwwttttj">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="wwwblog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          spring-校验框架整理
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-09-24 09:18:37 / 修改时间：09:20:47" itemprop="dateCreated datePublished" datetime="2020-09-24T09:18:37+08:00">2020-09-24</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="spring-效验架构整理"><a href="#spring-效验架构整理" class="headerlink" title="spring 效验架构整理"></a>spring 效验架构整理</h1><h2 id="1-spring-Validated"><a href="#1-spring-Validated" class="headerlink" title="1.spring @Validated"></a>1.spring @Validated</h2><h3 id="1-Validated-和-Valid-区别Validated带分组功能-而Valid没有实现-Validated-supporting-the-specification-of-validation-groups"><a href="#1-Validated-和-Valid-区别Validated带分组功能-而Valid没有实现-Validated-supporting-the-specification-of-validation-groups" class="headerlink" title="1 @Validated 和@Valid 区别Validated带分组功能 而Valid没有实现(@Validated supporting the specification of validation groups)"></a>1 @Validated 和@Valid 区别Validated带<code>分组</code>功能 而Valid没有实现(@Validated supporting the specification of validation groups)</h3><p> Variant of JSR-303 拥有以下注解<br> <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">AssertFalse  AssertTrue  DecimalMax DecimalMin</span><br><span class="line">Digits Email Future  FutureOrPresent Max Min</span><br><span class="line">Negative  NegativeOrZero  NotBlank NotEmpty</span><br><span class="line">NotNull Null Past PastOrPresent Pattern</span><br><span class="line">Positive PositiveOrZero Size ......</span><br></pre></td></tr></table></figure><br>自行了解.</p>
<h3 id="2-如何使用："><a href="#2-如何使用：" class="headerlink" title="2 如何使用："></a>2 如何使用：</h3><p>使用分组功能需要接口比如</p>
<a id="more"></a>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">配置文件</span><br><span class="line">@Configuration</span><br><span class="line">public class BeanValidatorConfiguration &#123;</span><br><span class="line"></span><br><span class="line">    &#x2F;**</span><br><span class="line">    *使用hibernate 效验 </span><br><span class="line">    *hibernate.validator.fail_fast 当出现一次错误，后面就不效验了</span><br><span class="line">    *如果只有一个效验器，可以不用配置</span><br><span class="line">    *&#x2F;</span><br><span class="line">    @Bean</span><br><span class="line">    public Validator validator()&#123;</span><br><span class="line">        ValidatorFactory validatorFactory &#x3D; Validation.byProvider( HibernateValidator.class )</span><br><span class="line">                .configure()</span><br><span class="line">                .addProperty( &quot;hibernate.validator.fail_fast&quot;, &quot;true&quot; )</span><br><span class="line">                .buildValidatorFactory();</span><br><span class="line">        return validatorFactory.getValidator();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#x2F;**</span><br><span class="line">*使用@Validated 注解。validator后处理，使所有有这个注解的类都会被aop切面</span><br><span class="line">*spring boot 默认配置了，可以不用加</span><br><span class="line">*&#x2F;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    public MethodValidationPostProcessor methodValidationPostProcessor()&#123;</span><br><span class="line">        MethodValidationPostProcessor methodValidationPostProcessor &#x3D; new MethodValidationPostProcessor();</span><br><span class="line">        methodValidationPostProcessor.setValidator(validator());</span><br><span class="line">        return methodValidationPostProcessor;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@NotNull(message &#x3D; &quot;类型不能为空&quot; )</span><br><span class="line">private Integer type;</span><br><span class="line">@NotBlank(message &#x3D; &quot;主题不能为空&quot; ,groups &#x3D;update.class )</span><br><span class="line">private String title;</span><br><span class="line">@NotBlank(message &#x3D; &quot;内容不能为空&quot;,groups &#x3D;insert.class )</span><br><span class="line">private String content;</span><br><span class="line">@Size(min &#x3D; 1,message &#x3D; &quot;不能为空&quot;)</span><br><span class="line">private List&lt;String&gt; stringList;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>需要注意的是使用<br>@Validated({insert.class})<br>只会使gourp=insert.class 的注解生效，而默认的default.class 不会生效，所以自定义的接口需要继承default接口 (public interface insert extends <code>Default</code> )<br/><br>继承前效验（content）,继承后效验 type,content,和stringList</p>
<hr>
<p><br/>全局的异常处理类增加</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">@ResponseBody</span><br><span class="line"> @ExceptionHandler(MethodArgumentNotValidException.class)</span><br><span class="line"> public Response handleParamValidException(MethodArgumentNotValidException e)&#123;</span><br><span class="line">   BindingResult bindingResult &#x3D; e.getBindingResult();</span><br><span class="line">     return Response.newFailResponse(UserResCode.PARAM_ERROR.getCode(), bindingResult.getFieldErrors().get(0).getDefaultMessage());</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-自定义注解"><a href="#3-自定义注解" class="headerlink" title="3 自定义注解"></a>3 自定义注解</h3><h4 id="自定义注解"><a href="#自定义注解" class="headerlink" title="自定义注解"></a>自定义注解</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Documented</span><br><span class="line">@Constraint(validatedBy &#x3D; &#123; &#125;)</span><br><span class="line">@Target(&#123; METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE &#125;)</span><br><span class="line">@Retention(RUNTIME)</span><br><span class="line">@Repeatable(List.class)</span><br><span class="line">public @interface NotBlank &#123;</span><br><span class="line">    ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>validatedBy</code> 中新建你自定的效验类 比如NotBlankValidtor<br>实现 ConstraintValidator 接口</p>
<p>public class NotBlankValidator implements ConstraintValidator&lt;NotBlank, CharSequence&gt; {<br>    @Override<br>    public boolean isValid(CharSequence charSequence, ConstraintValidatorContext constraintValidatorContext) {<br>        if ( charSequence == null ) {<br>            return true;<br>        }</p>
<pre><code>    return charSequence.toString().trim().length() &gt; 0;
&#125;</code></pre>
<p>}<br>源码分析</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">1.入口</span><br><span class="line"> ValidatorFactory validatorFactory &#x3D; Validation.buildDefaultValidatorFactory();</span><br><span class="line">  Validator validator &#x3D; validatorFactory.getValidator();</span><br><span class="line">  validator.validate(object)</span><br><span class="line"></span><br><span class="line">2.validate 方法</span><br><span class="line">  @Override</span><br><span class="line">	public final &lt;T&gt; Set&lt;ConstraintViolation&lt;T&gt;&gt; validate(T object, Class&lt;?&gt;... groups) &#123;</span><br><span class="line">		Contracts.assertNotNull( object, MESSAGES.validatedObjectMustNotBeNull() );</span><br><span class="line"></span><br><span class="line">		if ( !beanMetaDataManager.isConstrained( object.getClass() ) ) &#123;</span><br><span class="line">			return Collections.emptySet();</span><br><span class="line">		&#125;</span><br><span class="line">    &#x2F;&#x2F;此方法决定使用哪个group</span><br><span class="line">		ValidationOrder validationOrder &#x3D; determineGroupValidationOrder( groups );</span><br><span class="line">        &#x2F;&#x2F;此方法是获取实体的验证规则(上下文)</span><br><span class="line">		ValidationContext&lt;T&gt; validationContext &#x3D; getValidationContext().forValidate( object );</span><br><span class="line"></span><br><span class="line">		ValueContext&lt;?, Object&gt; valueContext &#x3D; ValueContext.getLocalExecutionContext(</span><br><span class="line">				object,</span><br><span class="line">				beanMetaDataManager.getBeanMetaData( object.getClass() ),</span><br><span class="line">				PathImpl.createRootPath()</span><br><span class="line">		);</span><br><span class="line"></span><br><span class="line">		return validateInContext( valueContext, validationContext, validationOrder );</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">determineGroupValidationOrder 方法如果没传入group 默认使用default.class group</span><br><span class="line">后面开始得到效验的顺序(getValidationOrder)</span><br><span class="line">将所有的group放入DefaultValidationOrder 类中</span><br><span class="line">groupList中 ,sequence 放入sequenceMap 中</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">继续进入validateInContext 方法中，然后进入</span><br><span class="line">validateConstraintsForCurrentGroup -&gt;validateConstraintsForDefaultGroup-&gt;</span><br><span class="line">validateConstraint-&gt;validateConstraints-&gt; validateSingleConstraint  到最终的效验方法</span><br><span class="line">可以看到isValid &#x3D; validator.isValid( validatedValue, constraintValidatorContext );</span><br><span class="line">调用了效验器的isValid 的方法。这里就是注解</span><br><span class="line">validatedBy 所实现的类中的isValid方法</span><br><span class="line"></span><br><span class="line">查看各注解的效验方法,可以查找注解加Validator后缀的类，例如：NotBlankValidator</span><br></pre></td></tr></table></figure>



<p>1.@GroupSequence({insert.class,update.class}) //分组顺序:略<br/><br>2.组合验证、跨参数验证、脚本验证器和混合验证 :略<br/><br>3.本地化、国际化:略<br/></p>
<blockquote>
<p><code>参考</code>： <a target="_blank" rel="noopener" href="https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#preface">Hibernate Validator 6.0.13.Final - JSR 380 Reference Implementation</a></p>
</blockquote>
<p> <code>总结</code>  推荐统一使用spring效验，功能强大,开发迅速。现阶段简单功能已满足需求。</p>
<hr>
<h2 id="2-oval-效验框架"><a href="#2-oval-效验框架" class="headerlink" title="2.oval 效验框架"></a>2.oval 效验框架</h2><h3 id="1-实体上加上oval-的注解-JSR-303"><a href="#1-实体上加上oval-的注解-JSR-303" class="headerlink" title="1   实体上加上oval 的注解 JSR-303"></a>1   实体上加上oval 的注解 JSR-303</h3><p><code>略</code></p>
<h3 id="2-使用"><a href="#2-使用" class="headerlink" title="2 使用"></a>2 使用</h3><p><code>不能使用</code> @Validated, 需要手动使用工具类调用 或@Valid（没有分组）<br>validate方法<br>如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">Controller:  </span><br><span class="line">String message &#x3D; ParamValidatorUtil.valid(object,&quot;insert&quot;);</span><br><span class="line"></span><br><span class="line">Utils:</span><br><span class="line">  public static String validProfile(Object object,String  profile) &#123;</span><br><span class="line">        Validator validator &#x3D; new Validator();</span><br><span class="line">        validator.disableAllProfiles();</span><br><span class="line">        validator.enableProfile(profile);</span><br><span class="line">        validator.enableProfile(&quot;default&quot;);</span><br><span class="line">        List&lt;ConstraintViolation&gt; validateResult &#x3D; validator.validate(object);</span><br><span class="line">        if (null!&#x3D;validateResult &amp;&amp; validateResult.size()&gt;0) &#123;</span><br><span class="line">            return validateResult.get(0).getMessage();</span><br><span class="line">        &#125;</span><br><span class="line">        return null;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<hr>
<p>全局异常处理：略</p>
<hr>
<p>同样我们看到源码中<code>profile</code> 需要支持<code>default</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;oval 分组实现</span><br><span class="line">  protected boolean isAnyProfileEnabled(final String[] profilesOfCheck, final String[] enabledProfiles) &#123;</span><br><span class="line">      &#x2F;&#x2F;如果传入参数没有分组，则使用默认，字段上方有profile  则会进行效验是否生效</span><br><span class="line">        if (enabledProfiles &#x3D;&#x3D; null) &#123;</span><br><span class="line">            &#x2F;&#x2F; use the global profile configuration</span><br><span class="line">            if (profilesOfCheck &#x3D;&#x3D; null || profilesOfCheck.length &#x3D;&#x3D; 0)</span><br><span class="line">                return isProfileEnabled(&quot;default&quot;);</span><br><span class="line"></span><br><span class="line">            for (final String profile : profilesOfCheck)</span><br><span class="line">                if (isProfileEnabled(profile))</span><br><span class="line">                    return true;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            &#x2F;&#x2F;如果传入参数有分组，则也会比较enabledProfiles 是否存在这个分组</span><br><span class="line">            &#x2F;&#x2F; use the local profile configuration</span><br><span class="line">            if (profilesOfCheck &#x3D;&#x3D; null || profilesOfCheck.length &#x3D;&#x3D; 0)</span><br><span class="line">                return ArrayUtils.containsEqual(enabledProfiles, &quot;default&quot;);</span><br><span class="line"></span><br><span class="line">            for (final String profile : profilesOfCheck)</span><br><span class="line">                if (ArrayUtils.containsEqual(enabledProfiles, profile))</span><br><span class="line">                    return true;</span><br><span class="line">        &#125;</span><br><span class="line">        return false;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>###3 自定义注解和方法</p>
<h4 id="自定义注解-1"><a href="#自定义注解-1" class="headerlink" title="自定义注解"></a>自定义注解</h4><p>1.首先自定义一个注解如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">@Documented</span><br><span class="line">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="line">@Target(&#123; ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD &#125;)</span><br><span class="line">@Constraint(checkWith &#x3D; NotNull.class)</span><br><span class="line">public @interface NotNullCheck &#123;</span><br><span class="line">    ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中<code>Constraint</code> 中标识 实现的类继承<code>AbstractAnnotationCheck</code><NotNullCheck><br>主方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public class NotNullCheck extends AbstractAnnotationCheck&lt;NotNull&gt; &#123;</span><br><span class="line">    </span><br><span class="line">    private static final long serialVersionUID &#x3D; 1L;</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;效验的主方法 validatedObject,被效验的对象，valueToValidate 被效验的值</span><br><span class="line"></span><br><span class="line">    public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context, final Validator validator) &#123;</span><br><span class="line">        return valueToValidate !&#x3D; null;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h4 id="自定义方法-ValidateWithMethod"><a href="#自定义方法-ValidateWithMethod" class="headerlink" title="自定义方法@ValidateWithMethod"></a>自定义方法@<code>ValidateWithMethod</code></h4><p>使用ValidateWithMethod 中设定methodName，然后在实体中新增一个同名的方法，返回true<br> @ValidateWithMethod(methodName = “notEmpty”,message =”不能为空”,parameterType = String.class)<br> private boolean notEmpty (String parm){<br>        if(parm==null){<br>            retrun true;<br>        }<br>        return StringUtils.isNotBlank(parm);<br> }</p>
<blockquote>
<p>参考：<a target="_blank" rel="noopener" href="http://oval.sourceforge.net/userguide.html">oval使用指南</a>  </p>
</blockquote>
<h2 id="优点：1-功能强大，自定义方法比较方便，还可以和groovy、beanshell、js、OGNL、JXPath、JRuby-整合-需引用对应的依赖"><a href="#优点：1-功能强大，自定义方法比较方便，还可以和groovy、beanshell、js、OGNL、JXPath、JRuby-整合-需引用对应的依赖" class="headerlink" title="优点：1.功能强大，自定义方法比较方便，还可以和groovy、beanshell、js、OGNL、JXPath、JRuby  整合(需引用对应的依赖)"></a><code>优点</code>：1.功能强大，自定义方法比较方便，还可以和groovy、beanshell、js、OGNL、JXPath、JRuby  整合(需引用对应的依赖)</h2><p>// 例如： @NotNull(when = “groovy:_this.fieldA != null”)</p>
<h2 id="缺点：spring-整合-麻烦-，使用人少，资料较少，maven最新只到2017年，后续没有更新，-profile-使用的是字符串、不是太友好。"><a href="#缺点：spring-整合-麻烦-，使用人少，资料较少，maven最新只到2017年，后续没有更新，-profile-使用的是字符串、不是太友好。" class="headerlink" title="缺点：spring 整合(麻烦)，使用人少，资料较少，maven最新只到2017年，后续没有更新， profile 使用的是字符串、不是太友好。"></a><code>缺点</code>：spring 整合(麻烦)，使用人少，资料较少，maven最新只到2017年，后续没有更新， profile 使用的是字符串、不是太友好。</h2>
    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/09/24/hello-world/" rel="prev" title="Hello World">
      <i class="fa fa-chevron-left"></i> Hello World
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/09/24/completable-%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B/" rel="next" title="completable_异步编程">
      completable_异步编程 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#spring-%E6%95%88%E9%AA%8C%E6%9E%B6%E6%9E%84%E6%95%B4%E7%90%86"><span class="nav-number">1.</span> <span class="nav-text">spring 效验架构整理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-spring-Validated"><span class="nav-number">1.1.</span> <span class="nav-text">1.spring @Validated</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-Validated-%E5%92%8C-Valid-%E5%8C%BA%E5%88%ABValidated%E5%B8%A6%E5%88%86%E7%BB%84%E5%8A%9F%E8%83%BD-%E8%80%8CValid%E6%B2%A1%E6%9C%89%E5%AE%9E%E7%8E%B0-Validated-supporting-the-specification-of-validation-groups"><span class="nav-number">1.1.1.</span> <span class="nav-text">1 @Validated 和@Valid 区别Validated带分组功能 而Valid没有实现(@Validated supporting the specification of validation groups)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%EF%BC%9A"><span class="nav-number">1.1.2.</span> <span class="nav-text">2 如何使用：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3"><span class="nav-number">1.1.3.</span> <span class="nav-text">3 自定义注解</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3"><span class="nav-number">1.1.3.1.</span> <span class="nav-text">自定义注解</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-oval-%E6%95%88%E9%AA%8C%E6%A1%86%E6%9E%B6"><span class="nav-number">1.2.</span> <span class="nav-text">2.oval 效验框架</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-%E5%AE%9E%E4%BD%93%E4%B8%8A%E5%8A%A0%E4%B8%8Aoval-%E7%9A%84%E6%B3%A8%E8%A7%A3-JSR-303"><span class="nav-number">1.2.1.</span> <span class="nav-text">1   实体上加上oval 的注解 JSR-303</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E4%BD%BF%E7%94%A8"><span class="nav-number">1.2.2.</span> <span class="nav-text">2 使用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3-1"><span class="nav-number">1.2.2.1.</span> <span class="nav-text">自定义注解</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E6%96%B9%E6%B3%95-ValidateWithMethod"><span class="nav-number">1.2.2.2.</span> <span class="nav-text">自定义方法@ValidateWithMethod</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BC%98%E7%82%B9%EF%BC%9A1-%E5%8A%9F%E8%83%BD%E5%BC%BA%E5%A4%A7%EF%BC%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E6%96%B9%E6%B3%95%E6%AF%94%E8%BE%83%E6%96%B9%E4%BE%BF%EF%BC%8C%E8%BF%98%E5%8F%AF%E4%BB%A5%E5%92%8Cgroovy%E3%80%81beanshell%E3%80%81js%E3%80%81OGNL%E3%80%81JXPath%E3%80%81JRuby-%E6%95%B4%E5%90%88-%E9%9C%80%E5%BC%95%E7%94%A8%E5%AF%B9%E5%BA%94%E7%9A%84%E4%BE%9D%E8%B5%96"><span class="nav-number">1.3.</span> <span class="nav-text">优点：1.功能强大，自定义方法比较方便，还可以和groovy、beanshell、js、OGNL、JXPath、JRuby  整合(需引用对应的依赖)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9%EF%BC%9Aspring-%E6%95%B4%E5%90%88-%E9%BA%BB%E7%83%A6-%EF%BC%8C%E4%BD%BF%E7%94%A8%E4%BA%BA%E5%B0%91%EF%BC%8C%E8%B5%84%E6%96%99%E8%BE%83%E5%B0%91%EF%BC%8Cmaven%E6%9C%80%E6%96%B0%E5%8F%AA%E5%88%B02017%E5%B9%B4%EF%BC%8C%E5%90%8E%E7%BB%AD%E6%B2%A1%E6%9C%89%E6%9B%B4%E6%96%B0%EF%BC%8C-profile-%E4%BD%BF%E7%94%A8%E7%9A%84%E6%98%AF%E5%AD%97%E7%AC%A6%E4%B8%B2%E3%80%81%E4%B8%8D%E6%98%AF%E5%A4%AA%E5%8F%8B%E5%A5%BD%E3%80%82"><span class="nav-number">1.4.</span> <span class="nav-text">缺点：spring 整合(麻烦)，使用人少，资料较少，maven最新只到2017年，后续没有更新， profile 使用的是字符串、不是太友好。</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">wwwttttj</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">8</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://gitee.com/wwwttttj" title="gitee → https:&#x2F;&#x2F;gitee.com&#x2F;wwwttttj" rel="noopener" target="_blank"><i class="fab fa-gitee fa-fw"></i>gitee</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wwwttttj</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
